package v1

import (
	"bc/dao"
	"bc/service"
	"bc/util"
	"bc/util/library/zstack"
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"io/ioutil"
	"net/http"
)

type vm struct {

}
func (t *vm)CreateTemp(c *gin.Context){

	byte,err := ioutil.ReadAll(c.Request.Body)
	defer c.Request.Body.Close()
	if err != nil {
		c.JSON(200,gin.H{
			"code":500,
			"msg":"数据有误，请重试",

		})
		return
	}
	mdata := make(map[string]interface{})
	err = json.Unmarshal(byte,&mdata)
	if err != nil {
		c.JSON(200,gin.H{
			"code":500,
			"msg":"数据格式有误",
		})
		return
	}
	fmt.Println(mdata)

}
func (t *vm)Create(c *gin.Context){

	param := make(map[string]map[string]interface{})
	param["params"] = make(map[string]interface{})

	if v,ok := c.GetPostForm("name");!ok{
		c.JSON(200,gin.H{
			"code":500,
			"msg":"error",
			"data":"请填写云主机名称",
		})
		return
	}else{
		param["params"]["name"] = v
	}

	if v,ok := c.GetPostForm("instanceOfferingUuid");!ok{
		c.JSON(200,gin.H{
			"code":500,
			"msg":"error",
			"data":"请选择计算规格",
		})
		return
	}else{
		param["params"]["instanceOfferingUuid"] = v
	}

	if v,ok := c.GetPostForm("imageUuid");!ok{
		c.JSON(200,gin.H{
			"code":500,
			"msg":"error",
			"data":"请选择镜像",
		})
		return
	}else{
		param["params"]["imageUuid"] = v
	}

	if v,ok := c.GetPostFormArray("l3NetworkUuids");!ok{
		c.JSON(200,gin.H{
			"code":500,
			"msg":"error",
			"data":"请选择三层网络",
		})
		return
	}else{
		param["params"]["l3NetworkUuids"] = v
	}


	byte,err := json.Marshal(param)
	if err != nil{
		c.JSON(200,gin.H{
			"code":500,
			"msg":"error",
			"data":"请重试",
		})
		return
	}
	str,err := zstack.VM.Create(string(byte), 0, 0)
	if err !=nil{
		c.JSON(200,gin.H{
			"code":500,
			"msg":"error",
			"data":"请重试",
		})
		return
	}
	c.JSON(200,gin.H{
		"code":200,
		"msg":"创建成功",
		"data":str,
	})

}
func (t *vm)CreateVmCallBack(c *gin.Context){
	snId := c.Query("sn_id")
	uid := c.Query("uid")
	byte,err := ioutil.ReadAll(c.Request.Body)
	defer c.Request.Body.Close()

	if err != nil{
		panic(err)
	}
	d := make(map[string]interface{})
	err = json.Unmarshal(byte,&d)

	if v,ok := d["error"];ok{
		fmt.Println(v.(map[string]interface{})["elaboration"])
		return
	}

	new_d := make(map[string]interface{})
	new_d = d["inventory"].(map[string]interface{})
	if err != nil{
		panic(err)
	}

	new_d["sn_id"] = util.StrToInt(nil,snId)
	new_d["uid"] = util.StrToInt(nil,uid)
	fmt.Println(new_d)
	b := service.Vm.Create(new_d)
	if b{
		fmt.Println(b)
	}

}

func (t *vm)GetAddress(c *gin.Context){
	snId := c.Param("sn_id")
	fmt.Println(snId)
	dao.Vm.SnId = util.StrToInt(nil,snId)
	vm,err := dao.Vm.FindUuid()
	if err != nil {
		c.JSON(200,gin.H{
			"code":500,
			"msg":"error",
			"data":"请重试",
		})
	}
	console := zstack.Console{}
	res, err := console.GetConsole(vm.Uuid)

	if err !=nil{
		c.JSON(200,gin.H{
			"code":500,
			"msg":"error",
			"data":"请重试",
		})
		return
	}
	var result util.Response
	result.Data = res

	c.JSON(http.StatusOK, result.ReturnOK())

}
var Vm = &vm{}
